const Controller = require('egg').Controller;

class UserController extends Controller {
    appid = `wx81b937195945b472`
    apps = `7cc1cb020a47a94b3a20e25054de498f`
    async show() {
        const ctx = this.ctx;
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appid}&secret=${this.apps}&js_code=${ctx.request.body.code}&grant_type=authorization_code`
        const result = await ctx.app.curl(url, {
            dataType: 'json',
        });
        ctx.status = 200
        ctx.data = result.data
        ctx.msg = "获取成功"

    }

    async getToken() {
        const ctx = this.ctx;
        const url = `https://api.weixin.qq.com/cgi-bin/token?appid=${this.appid}&secret=${this.apps}&grant_type=client_credential`
        const result = await ctx.app.curl(url, {
            dataType: 'json',
        });
        
        ctx.status = 200
        ctx.data = result.data
        ctx.msg = "获取成功"

    }
    async info() {
        const ctx = this.ctx;
        var { openid } = ctx.request.body;
        var resdata = await ctx.model.User.findOne({
            where: {
                wxOpenId: openid
            }
        });
        ctx.status = 200;
        ctx.data = resdata;
        if (resdata) {
            ctx.msg = "获取成功"

        } else {
            ctx.status = 201;
            ctx.msg = "获取失败"
        }
    }
    async decrypt() {
        const ctx = this.ctx;
        var { encryptedData, iv, sessionKey, openid } = ctx.request.body;
        const data = await ctx.service.wx.decrypt(this.appid, sessionKey, encryptedData, iv);
        const where = {
            wxOpenId: openid
        }
        var resdata = await ctx.model.User.findOne({
            where: where
        });
        if (resdata) {

            await resdata.update({ userPhone: data.phoneNumber });
            // user = await ctx.model.User.create({ wxOpenId: openid, password: "admin" });
        } else {
            await ctx.model.User.create({ wxOpenId: openid, userPhone: data.phoneNumber });
        }
        ctx.status = 200;
        ctx.data = data;
        ctx.msg = "获取成功"

    }
}

module.exports = UserController;